package src.ee.ioc.smaug.world.evolution;

/**
 * Different kinds of string distances
 * 
 * @author Margarita Spichakova
 * 
 */
public class StringDistances {

    /**
     * Apply different string distances according to parameter
     * @param s1 s1 one word  
     * @param s2 second word
     * @return similarity value
     */
    public static int apply(String s1, String s2) {
        int sim = 0;
        switch (EnvDescription.FFtype) {
        case HAMMING_DISTANCE:
            sim = hammingDistanceSimilarity(s1, s2);
            break;
        case MAX_PREFIX:
            sim = maximalEqualPrefix(s1, s2);
            break;
        }

        return sim;
    }

    /**
     * Returns the number of the equal chars in same positions
     * @param s1 one word   
     * @param s2 second word
     * @return similarity value
     */
    private static int hammingDistanceSimilarity(String s1, String s2) {
        int sim = 0;
        if (s1.length() <= s2.length()) {
            for (int i = 0; i < s1.length(); i++) {
                if (s1.charAt(i) == s2.charAt(i)) {
                    sim++;
                }
            }
        } else {
            for (int i = 0; i < s2.length(); i++) {
                if (s1.charAt(i) == s2.charAt(i)) {
                    sim++;
                }
            }
        }

        return sim;
    }

    /**
     * Returns the length of maximal equal prefix. Work ends when first error found
     * @param s1 string one
     * @param s2 string two
     * @return length of maximal equal prefix
     */
    private static int maximalEqualPrefix(String s1, String s2) {
        int prefix = 0;
        if (s1.length() <= s2.length()) {
            for (int i = 0; i < s1.length(); i++) {
                if (s1.charAt(i) == s2.charAt(i))
                    prefix++;
                else
                    return prefix;
            }
        } else {
            for (int i = 0; i < s2.length(); i++) {
                if (s1.charAt(i) == s2.charAt(i))
                    prefix++;
                else
                    return prefix;

            }
        }

        return prefix;

    }

}
